package com.fplugin.ushare;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.embedding.engine.plugins.activity.ActivityAware;
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** UsharePlugin */
public class UsharePlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
  private String TAG = "USharePlugin=>TAG";
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private MethodChannel channel;
  private Umengshare umengShare;
  private static Activity activity;
  private static Context context;

  @Override
  public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
    channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "ushare");
    context = flutterPluginBinding.getApplicationContext();
    channel.setMethodCallHandler(this);
  }

  @Override
  public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
    try {
      switch (call.method) {
        case "init":
          init(call, result);
          break;
        case "share":
          doShare(call, result);
        default:
          result.notImplemented();
          break;
      }} catch (Exception e) {
        e.printStackTrace();
      }
  }

  private void init(@NonNull MethodCall call, @NonNull final Result result) throws Exception {
    String appKey = call.argument("appKey");
    String channel = call.argument("channel");
    String wxAppid = call.argument("wxAppid");
    String wxSecret = call.argument("wxSecret");
    String qqAppid = call.argument("qqAppid");
    String weiboAppid = call.argument("weiboAppid");

    boolean loggerEnable = call.argument("loggerEnable");

    umengShare = new Umengshare(activity, context);

    UMConfigure.init(context, appKey, channel, UMConfigure.DEVICE_TYPE_PHONE, null);
    UMConfigure.setLogEnabled(loggerEnable);

//    try {
//      ActivityInfo activityInfo = activity.getPackageManager().getActivityInfo(activity.getComponentName(), PackageManager.GET_META_DATA);
//      ApplicationInfo applicationInfo= activity.getPackageManager().getApplicationInfo(activity.getPackageName(),PackageManager.GET_META_DATA);
//      String value = applicationInfo.metaData.getString("qqappid");
//      String aa = value;
//    } catch (PackageManager.NameNotFoundException e) {
//    }
    PlatformConfig.setWeixin(wxAppid, wxSecret);
    PlatformConfig.setWXFileProvider("com.kanman.allfree.fileprovider");
    PlatformConfig.setQQZone(qqAppid, "12");
    PlatformConfig.setQQFileProvider("com.kanman.allfree.fileprovider");
    PlatformConfig.setSinaWeibo(weiboAppid, "123", "456");
    PlatformConfig.setSinaFileProvider("com.kanman.allfree.fileprovider");

    if(Build.VERSION.SDK_INT >= 23) {
      String[] mPermissionList = new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE };
      ActivityCompat.requestPermissions(activity, mPermissionList, 123);
    }

    Log.d(TAG,"初始化成功");
  }

  private void doShare(@NonNull MethodCall call, @NonNull final Result result) throws Exception {
    umengShare.shareUrl(call, result);
  }

  @Override
  public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
    channel.setMethodCallHandler(null);
  }

  /**
   * This {@code ActivityAware} {@link FlutterPlugin} is now associated with an {@link Activity}.
   *
   * <p>This method can be invoked in 1 of 2 situations:
   *
   * <ul>
   *   <li>This {@code ActivityAware} {@link FlutterPlugin} was just added to a {@link
   *       FlutterEngine} that was already connected to a running {@link Activity}.
   *   <li>This {@code ActivityAware} {@link FlutterPlugin} was already added to a {@link
   *       FlutterEngine} and that {@link FlutterEngine} was just connected to an {@link Activity}.
   * </ul>
   * <p>
   * The given {@link ActivityPluginBinding} contains {@link Activity}-related references that an
   * {@code ActivityAware} {@link FlutterPlugin} may require, such as a reference to the actual
   * {@link Activity} in question. The {@link ActivityPluginBinding} may be referenced until either
   * {@link #onDetachedFromActivityForConfigChanges()} or {@link #onDetachedFromActivity()} is
   * invoked. At the conclusion of either of those methods, the binding is no longer valid. Clear
   * any references to the binding or its resources, and do not invoke any further methods on the
   * binding or its resources.
   *
   * @param binding
   */
  @Override
  public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) {
    activity = binding.getActivity();
    binding.addActivityResultListener(resultListener);
  }

  @Override
  public void onDetachedFromActivityForConfigChanges() {

  }

  @Override
  public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) {

  }

  @Override
  public void onDetachedFromActivity() {

  }

  private final PluginRegistry.ActivityResultListener resultListener =
      new PluginRegistry.ActivityResultListener() {
      @Override
      public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
        UMShareAPI.get(activity).onActivityResult(requestCode, resultCode, data);
        return false;
      }
  };

}
